using System;
using System.Collections.Generic;

namespace SmartSite.Frame
{
    public static class BaseFrameExtention
    {
        public static UInt16 CalculationCRC(this IList<byte> buffer, int index, int count)
        {
            if (buffer == null)
                throw new ArgumentNullException(nameof(buffer));
                
            UInt16 usCrc = 0xFFFF;

            for (int i = index; count > 0; i++, count--)
            {
                usCrc ^= (UInt16)buffer[i];
                for (int j = 0; j < 8; j++)
                {
                    int poly = (usCrc & 1) == 1 ? 0xA001 : 0;
                    usCrc >>= 1;
                    usCrc ^= (UInt16)poly;
                }
            }

            return usCrc;
        }

        public static int ToTakeUpBytes(this BitUnit bitCount) => (bitCount + 7) >> 3;
    }
}